package com.yazi.mxz.behavior.quartz;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.Paging;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.hibernate.SearchingFactory;
import com.yazi.mxz.behavior.common.ValueFactory;
import com.yazi.mxz.behavior.entity.beans.Store;
import com.yazi.mxz.behavior.entity.enums.DataSyncType;
import com.yazi.mxz.behavior.entity.repository.DataSyncLog;
import com.yazi.mxz.behavior.repository.StoreRepository;
import com.yazi.mxz.behavior.service.StoreService;

/**
 * 店铺数据同步(from oracle to mongodb)
 * @author mo_yq5
 * @date 2015-5-28
 */
public class StoreSyncQuartz extends SyncQuartzAbstract {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public static boolean reset = false;
	
	@Resource
	StoreRepository storeRepository;
	
	@Resource
	StoreService storeService;
	
	public boolean work() {
		if (isWorking) {
			logger.info("店铺 sync working");
			return false;
		}

		if (reset) {
			reset = false;			
			logger.info("店铺 del all: {}", storeRepository.count());
			dataSyncLogRepository.delete(DataSyncType.STORE.ordinal());
			storeRepository.deleteAll();
		}
		
		logger.info("店铺 sync start：{}", storeRepository.count());
		
		isWorking = true;
		amount = 0;
		
		sycLog = dataSyncLogRepository.findOne(DataSyncType.STORE.ordinal());
		if (null == sycLog) {
			sycLog = new DataSyncLog();
			sycLog.setId(DataSyncType.STORE.ordinal());
			sycLog.setLastTime(-1L);
			dataSyncLogRepository.insert(sycLog);
		}
		
		// 最后更新的那条记录的时间作为下次同步的时间依据
		long latestTime = 0;
		
		Searching si = SearchingFactory.createSearching("updateTime", true, 1);
		
		Page<Store> page;
		
		try {
			
			page = storeService.listByGtUpdateTime(sycLog.getLastTime(), si);		
			if (page.getPaging().getTotalResult() == 0) {
				latestTime = DateUtil.getTimeStamp();
				
			} else {
				
				latestTime = page.getList().get(0).getUpdateTime();
				
				si.setPageSize(Searching.MAX_PAGE_SIZE);
				checkStore(si);
			}
			
			sycLog.setLastTime(latestTime);
			dataSyncLogRepository.save(sycLog);
			logger.info("店铺 sync end: {}", amount);
			
		} catch (Exception e) {
			logger.error("店铺同步异常：", e);
			return false;
		} finally {
			isWorking = false;
		}
		return true;
	}
	
	private void checkStore(Searching si) {
		
		Page<Store> page = storeService.listByGtUpdateTime(sycLog.getLastTime(), si);
		List<Store> list = page.getList();
    	for (Store store : list) {

    		storeRepository.delete(store.getStoreId());
    		if (!store.getIsOpen()) {
    			// 已关闭的店铺
    			logger.debug("店铺 sync -> closed: {},{}", store.getStoreId(), store.getName());
    			continue;
    		}
    		
    		logger.info("店铺 sync: {},{}", store.getStoreId(), store.getName());
    		
    		amount++;
    		
    		// store of mongodb
    		com.yazi.mxz.behavior.entity.repository.Store store0mg = new com.yazi.mxz.behavior.entity.repository.Store();
    		ValueFactory.combine(store, store0mg);
    		
    		if (null != store.getLat() && null != store.getLng()) {
    			//store0mg.setLocation(new GeoJsonPoint(store0mg.getLng().doubleValue(), store0mg.getLat().doubleValue()));
    			store0mg.setLocation(new double[]{store.getLng().doubleValue(), store.getLat().doubleValue()});
    		}
    		
    		//...
    		
    		storeRepository.insert(store0mg);
		}
    	
    	Paging pi = page.getPaging();
    	if (pi.getNowPage() < pi.getTotalPage()) {
    		si.setNowPage(pi.getNowPage() + 1);
    		checkStore(si);
    	}
	}

}
